package com.maidou.qiantai.interceptor;

import com.maidou.qiantai.common.constant.HeritageSiteConstant;
import com.maidou.qiantai.common.constant.RedisEnum;
import com.maidou.qiantai.common.constant.TokenEnum;
import com.maidou.qiantai.common.utils.jwt.JwtUtils;
import com.maidou.qiantai.common.utils.jwt.MatchTokenGeneratorUtils;
import com.maidou.qiantai.exception.customizationException.AccessTokenAuthFailException;
import com.maidou.qiantai.exception.customizationException.DataLackException;
import com.maidou.qiantai.exception.customizationException.RefreshTokenRefreshFailException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {
//    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws NoSuchAlgorithmException {
        String accessToken = request.getHeader(TokenEnum.ACCESS_TOKEN.getValue());
        if (ObjectUtils.isEmpty(accessToken)){
            throw new AccessTokenAuthFailException();
        }
        try {
            if (!JwtUtils.validateToken(accessToken)) {
                throw new AccessTokenAuthFailException();
            }
        }catch (Exception e){
            throw new AccessTokenAuthFailException();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
//        threadLocal.remove();
    }
}